package zl.ordermanager.controller;

import java.util.List;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import zl.ordermanager.utils.ConfigUtil;
import zl.ordermanager.utils.IpUtil;
import zl.ordermanager.utils.MD5Util;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.ERoles;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SessionInfo;
import zl.ordermanager.vo.User;
import zl.ordermanager.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(User user, HttpSession session, HttpServletRequest request) {
		if (user.getUsername().equals("admin")) {
			if (userService.getByUsername(user.getUsername()) == null) {
				User adminUser = new User();
				adminUser.setUsername("admin");
				adminUser.setPassword(MD5Util.getMD5("admin"));
				adminUser.setRealname("张宾");
				adminUser.setRole(ERoles.ADMINISTRATOR.getRole());
				try {
					userService.add(adminUser);
				} catch (Exception e) {
					return new ModelAndView("login");
				}
			}
		}
		
		User u = userService.login(user);
		if (u != null) {

			SessionInfo sessionInfo = new SessionInfo();
			BeanUtils.copyProperties(u, sessionInfo);
			sessionInfo.setIp(IpUtil.getIpAddr(request));
			session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);

			return new ModelAndView("redirect:/");
		} else {
			if (logger.isInfoEnabled()) {
				logger.info("login(User, HttpSession, HttpServletRequest) - User or Password Error!");
			}

			return new ModelAndView("login", "error", "用户名或密码错误。");
		}
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(User user, HttpSession session, HttpServletRequest request) {
		session.invalidate();
		return new ModelAndView("login");
	}

	@RequestMapping("/showList")
	public String showList(PageHelper pageHelper, Model model) {
		DataGrid<User> dataGrid = userService.dataGrid(pageHelper);
		List<User> userList = dataGrid.getList();
		long totalCount = dataGrid.getTotal();

		model.addAttribute("userList", userList);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageHelper", pageHelper);

		return "userList";
	}

	@RequestMapping("/showAdd")
	public String showAdd(Model model) {
		model.addAttribute("roleList", ERoles.values());
		return "userAdd";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(User user) {
		try {
			userService.add(user);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/showEdit/{userId}")
	public String showEdit(@PathVariable("userId") Integer userId, Model model) {
		User user = userService.get(userId);
		model.addAttribute("user", user);
		model.addAttribute("roleList", ERoles.values());
		return "userEdit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView edit(User user) {
		try {
			userService.edit(user);
		} catch (Exception e) {
			return ajaxDoneError(e.getMessage());
		}
		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/delete/{userId}")
	public ModelAndView delete(@PathVariable("userId") Integer userId) {

		userService.delete(userId);

		return ajaxDoneSuccess("操作成功");
	}

	@RequestMapping("/showEditCurUserPwd")
	public String showEditCurUserPwd() {
		return "editCurUserPwd";
	}

	@RequestMapping(value = "/editCurUserPwd", method = RequestMethod.POST)
	public ModelAndView editCurUserPwd(HttpSession session, String oldPassword, String newPassword) {
		if (session != null) {
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
			if (sessionInfo != null) {
				if (userService.editCurUserPwd(sessionInfo, oldPassword, newPassword)) {
					return ajaxDoneSuccess("操作成功");
				} else {
					return ajaxDoneError("旧密码输入错误，请重新输入！");
				}
			} else {
				return ajaxDoneTimeout("登录超时，请重新登录！");
			}
		} else {
			return ajaxDoneTimeout("登录超时，请重新登录！");
		}
	}
}
